package Exer;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import java.util.Scanner;

public class StudentTest {

    /**
     * 键盘录入学生信息，保存到集合List中。
     * 使用ArrayList
     * 循环录入：1：继续 0：结束
     * 遍历集合
     */
    public static void main(String[] args) {

        ArrayList<Student> studentArrayList = null;
        try (Scanner scanner = new Scanner(System.in)) {
            int input;
            String name;
            int age;
            studentArrayList = new ArrayList<>();
            while (true) {
                System.out.println("是否继续录入？ 1(继续) / 0(结束)");
                input = scanner.nextInt();
                if (input == 1) {
                    System.out.print("姓名：");
                    name = scanner.next();
                    System.out.print("年龄：");
                    age = scanner.nextInt();

                    studentArrayList.add(new Student(name, age));

                } else if (input == 0)
                    break;
                else throw new RuntimeException("输入不合法！");
            }
        } finally {
            assert studentArrayList != null;
            for (Student stu : studentArrayList) {
                System.out.println(stu);
            }
        }


    }

    /**
     * 创建集合，集合存放随机生成的30个小写字母
     */
    @Test
    public void testCount() {
        Random random = new Random();

        ArrayList<String> arrayList = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            char num = (char) (random.nextInt(26) + 'a');
            arrayList.add(String.valueOf(num));
        }
        System.out.println(arrayList);
        System.out.println("a 元素的出现次数为：" + listTest(arrayList, "a"));
        System.out.println("b 元素的出现次数为：" + listTest(arrayList, "b"));
        System.out.println("c 元素的出现次数为：" + listTest(arrayList, "c"));
        System.out.println("x 元素的出现次数为：" + listTest(arrayList, "x"));


    }

    /**
     * 统计集合中指定元素出现的次数
     *
     * @param list 集合
     * @param s    指定元素
     * @return 指定元素出现的次数
     */
    public static int listTest(Collection<String> list, String s) {
        if (!list.contains(s))
            return 0;
        int count = 0;
        for (String string :
                list) {
            if (s.equals(string))
                count++;
        }
        return count;
    }
}
